/*
 * Created on Sat Oct 07 2017
 * Copyright (c) 2017 jianglinjie
 */
'use strict';
import PasswordService from '../../src/services/password';
import { 
  registerWithUserName,
  registerWithPhone,
  loginWithAccount,
} from './ServiceHelper';
import Random from 'random-js';
import { ErrorCode } from '../../src/constants';
import { GlobalDefines } from '../../src/constants';
import { CaptchaBusiness }  from '../../src/constants';
import { getCaptchaRedisKey } from '../../src/utils/CaptchaUtils';
import redis from '../../src/redis';
import CaptchaService from '../../src/services/captcha';
import { User } from '../../src/db/models';

test('RESET_PASSWORD', async () => {
  let phone = '1' + (new Random()).string(10, '0123456789');
  let oldPass = '123456';
  let newPass = 'abcdef';
  await registerWithPhone(phone, oldPass);
  let captchaResult = await CaptchaService.request({
    phone: phone,
    business: CaptchaBusiness.RESET_PASSWORD
  });

  let redisKey = getCaptchaRedisKey(phone, CaptchaBusiness.RESET_PASSWORD);
  let captcha = await redis.getAsync(redisKey);

  if (captcha !== captchaResult.captcha) {
    throw new Error('reset password captcha not equal to redis cache');
  }

  await PasswordService.resetPassword({
    phone: phone,
    captcha: captchaResult.captcha,
    newPass: newPass
  });

  await loginWithAccount(phone, newPass);
  let userDoc = await User.findOne({ phone: phone });
  expect(userDoc.pwd).toMatch(newPass);
});

test('MODIFY_PASSWORD', async () => {
  let userName = 'T' + (new Random()).string(10);
  let oldPass = '123456';
  let newPass = 'abcdef';
  //先用旧密码注册
  let user = await registerWithUserName(userName, oldPass);

  try {
    //密码不变
    await PasswordService.modify({
      uid: user.uid,
      oldPass: oldPass,
      newPass: oldPass
    });
  } catch (error) {
    expect(error[GlobalDefines.CUSTOM_ERROR_CODE_KEY]).toMatch(ErrorCode.PASSWORD_NOT_CHANGE);
  }

  await PasswordService.modify({
    uid: user.uid,
    oldPass: oldPass,
    newPass: newPass
  });

  //用新密码登录
  await loginWithAccount(userName, newPass);
  let userDoc = await User.findOne({ userName: userName });
  expect(userDoc.pwd).toMatch(newPass);
});